import dayjs from 'dayjs'
import { addVehicle, queryVehicleDetail, editVehicle } from '../../services/vehicle'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentId:"",
    vehicleInfo:{},
    showUseCharacter:false,
    useCharacterColumns:['非营运','营运'],
    currentUseCharacter:'非营运',
    plateNoErrorMsg:"",
    vehicleTypeErrorMsg:"",
    modelErrorMsg:"",
    mileageErrorMsg:"",
    access_token:"",

    showIssueDate:false,
    showRegisterDate: false,
    issueCurrentDate: dayjs().valueOf(),
    registerCurrentDate: dayjs().valueOf(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    // appid: 'wxb0b4765420d99fcf',
    // secret: 'dbbc9bf1d11fe1fdcf79608f22e1c02d'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { currentId } = options
    this.setData({
      currentId: currentId || ""
    })
    if( currentId ){
      this.getVehicleDetail(currentId)
    }
    this.getWxToken()
  },

  onShow(){

  },

  async getVehicleDetail(id){
    let detailRes = await queryVehicleDetail(id)
    if(detailRes.code === 200){
      this.setData({
        vehicleInfo: detailRes.data
      })
    }
  },

  getWxToken(){
    const _this = this
    let appid = wx.getStorageSync('appid') 
    let secret = wx.getStorageSync('secret') 
    wx.request({
      url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`,
      method: "get",
      success: (res) => {
        console.log("wxToken>>>res>>>", res)
        let access_token = res.data.access_token
        this.setData({
          access_token
        })
      },
    })
  },

  // ===========onchange事件===============
  onChangePlateNo(event){
    let plateNoErrorMsg = ""
    if(!event.detail){
      plateNoErrorMsg = "车牌号码不能为空,请输入!"
    }

    this.setData({
      ['vehicleInfo.name']: event.detail,
      ['vehicleInfo.plateNo']: event.detail,
      plateNoErrorMsg
    })
  },

  onChangeVehicleType(event){
    let vehicleTypeErrorMsg = ""
    if(!event.detail){
      vehicleTypeErrorMsg = "车辆型号不能为空,请输入!"
    }

    this.setData({
      ['vehicleInfo.vehicleType']: event.detail,
      vehicleTypeErrorMsg
    })
  },

  onChangeModel(event){
    let modelErrorMsg = ""
    if(!event.detail){
      modelErrorMsg = "品牌不能为空,请输入!"
    }
    this.setData({
      ['vehicleInfo.model']: event.detail,
      modelErrorMsg
    })
  },

  onChangeMileage(event){
    let mileageErrorMsg = ""
    if(!event.detail){
      mileageErrorMsg = "里程数不能为空,请输入!"
    }
    this.setData({
      ['vehicleInfo.mileage']: event.detail,
      mileageErrorMsg
    })
  },


  onChangeOwner(event){
    this.setData({
      ['vehicleInfo.owner']: event.detail
    })
  },

  onChangeEngineNo(event){
    this.setData({
      ['vehicleInfo.engineNo']: event.detail
    })
  },

  onChangeVin(event){
    this.setData({
      ['vehicleInfo.vin']: event.detail
    })
  },

  // ========使用性质Begin==========
  chooseUseCharacter(){
    this.setData({
      showUseCharacter: true
    })
  },
  handleUseCharacter(){
    this.setData({
      showUseCharacter: true
    })
  },
  onChangeUseCharacter(info){
    this.setData({
      currentUseCharacter: info.detail.value
    })
  },
  onCancelUseCharacter(){
    this.setData({
      showUseCharacter: false,
      currentUseCharacter:''
    })
  },
  onConfirmUseCharacter(){
    this.setData({
      showUseCharacter: false,
      ['vehicleInfo.useCharacter']: this.data.currentUseCharacter
    })
  },
  // ============使用性质End====================

  chooseIssueDate(){
    this.setData({
      issueCurrentDate: this.data.vehicleInfo.issueDate ?  dayjs( this.data.vehicleInfo.issueDate).valueOf() : dayjs().valueOf(),
      showIssueDate: true
    })
  },

  handleIssueDate(){
    this.setData({
      issueCurrentDate: this.data.vehicleInfo.issueDate ?  dayjs( this.data.vehicleInfo.issueDate).valueOf() : dayjs().valueOf(),
      showIssueDate: true
    })
  },

  onCancelIssueDate(){
    this.setData({
      showIssueDate: false
    })
  },

  onIssueDateInput(value){
    this.setData({
      issueCurrentDate: value.detail
    })
  },

  onConfirmIssueDate(value){
    const date = dayjs(value.detail).format('YYYY-MM-DD')
    this.setData({
      showIssueDate: false,
      ['vehicleInfo.issueDate']: date
    })
  },

  // ==================
  chooseRegisterDate(){
    this.setData({
      // registerCurrentDate: this.data.vehicleInfo.registerDate || new Date().getTime(),
      registerCurrentDate: this.data.vehicleInfo.registerDate ?  dayjs( this.data.vehicleInfo.registerDate).valueOf() : dayjs().valueOf(),
      showRegisterDate: true
    })
  },

  handleRegisterDate(){
    this.setData({
      showRegisterDate: true
    })
  },

  onCancelRegisterDate(){
    this.setData({
      showRegisterDate: false
    })
  },

  onRegisterDateInput(value){
    this.setData({
      registerCurrentDate: value.detail
    })
  },

  onConfirmRegisterDate(value){
    const date = dayjs(value.detail).format('YYYY-MM-DD')
    this.setData({
      showRegisterDate: false,
      ['vehicleInfo.registerDate']: date
    })
  },

  async confirmInfo(){
    if(!this.data.vehicleInfo.plateNo){
      let plateNoErrorMsg = "车牌号码不能为空,请输入!"
      this.setData({
        plateNoErrorMsg
      })
      return
    }else if(!this.data.vehicleInfo.vehicleType){
      let vehicleTypeErrorMsg = "车辆类型不能为空,请输入!"
      this.setData({
        vehicleTypeErrorMsg
      })
      return
    }else if(!this.data.vehicleInfo.model){
      let modelErrorMsg = "品牌类型不能为空,请输入!"
      this.setData({
        modelErrorMsg
      })
      return
    } else if(!this.data.vehicleInfo.mileage){
      let mileageErrorMsg = "里程数不能为空,请输入!"
      this.setData({
        mileageErrorMsg
      })
      return
    }

    if(this.data.vehicleInfo.id){
      let editRes = await editVehicle(this.data.vehicleInfo)
      if(editRes.code === 200){
        wx.navigateBack()
      }
    }else{
      let addRes = await addVehicle(this.data.vehicleInfo)
      if(addRes.code === 200){
        wx.navigateBack()
      }
    }
  },

  driverSuccess(event){
    console.log("event>>>",event)
    let vehicleData = event.detail
    let vehicleInfo = {}
    vehicleInfo.name = vehicleData.plate_num.text || ""
    vehicleInfo.plateNo = vehicleData.plate_num.text || "" //车牌号
    vehicleInfo.vehicleType = vehicleData.vehicle_type.text || "" //车辆类型
    vehicleInfo.owner = vehicleData.owner.text || "" //所有人
    vehicleInfo.addr = vehicleData.addr.text || "" //地址
    vehicleInfo.useCharacter = vehicleData.use_character.text || "" //使用性质
    vehicleInfo.model = vehicleData.model.text || "" //品牌型号
    vehicleInfo.vin = vehicleData.vin.text || "" //vin
    vehicleInfo.engineNo = vehicleData.engine_num.text || "" //发动机号码
    vehicleInfo.issueDate = vehicleData.issue_date.text || "" //发证日期
    vehicleInfo.registerDate = vehicleData.register_date.text || "" //注册日期

    console.log("vehicleInfo>>>", vehicleInfo)
    this.setData({
      vehicleInfo
    })
  }
})